package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
public class AutoFill_2_Aspect {
    @Before("@annotation(com.sky.annotation.AutoFill)&&execution(* com.sky.mapper.*.*(*))")
    public void AutoFill_2(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //获得方法签名，得到方法参数和注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        //获得注解
        OperationType value = annotation.value();
        //通过joinpoint获得的参数列表
        Object[] args = joinPoint.getArgs();
        //只有一个参数
        Object arg = args[0];
        //四个类型都在arg里面，下载判断注解类型去运行方法后和赋值
        if (value == OperationType.INSERT) {
            //
            Method createTime = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method updateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method createUser = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method updateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            //
            createTime.invoke(arg, LocalDateTime.now());
            updateTime.invoke(arg, LocalDateTime.now());
            createUser.invoke(arg, BaseContext.getCurrentId());
            updateUser.invoke(arg, BaseContext.getCurrentId());
        } else {
            Method updateTime = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method updateUser = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            updateTime.invoke(arg, LocalDateTime.now());
            updateUser.invoke(arg, BaseContext.getCurrentId());

        }


    }
}
